'use client';

import { useLocale } from 'use-intl';
import { useTransition } from 'react';
import classNames from 'classnames';
import { usePathname } from 'next-intl/client';
import { useSearchParams } from 'next/navigation';

export default function TranslateItem(
  this: any,
  { ulClass }: { ulClass?: string },
) {
  const locale = useLocale();
  const [isPending, startTransition] = useTransition();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  function onClickTranslate(value: string) {
    const params = searchParams.toString();
    const url = params
      ? `/${value}${pathname}?${params}`
      : `/${value}${pathname}`;

    startTransition(() => {
      location.replace(url);
    });
  }

  return (
    <ul className={classNames('navbar-nav', ulClass)}>
      <li className="nav-item dropstart">
        <a
          className="nav-link"
          role="button"
          data-bs-toggle="dropdown"
          aria-expanded="false"
        >
          <i className="bi bi-translate"></i>
        </a>
        <ul
          className="dropdown-menu text-center"
          style={{
            ['--bs-dropdown-min-width' as string]: '8rem',
          }}
        >
          <button
            disabled={isPending}
            onClick={onClickTranslate.bind(this, 'en')}
            type="button"
            className={classNames('dropdown-item d-flex align-items-center', {
              active: locale === 'en',
            })}
          >
            {isPending && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            English
            {locale === 'en' && <i className="bi bi-check2 ms-2"></i>}
          </button>

          <button
            disabled={isPending}
            onClick={onClickTranslate.bind(this, 'zh')}
            type="button"
            className={classNames('dropdown-item d-flex align-items-center', {
              active: locale === 'zh',
            })}
          >
            {isPending && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            简体中文
            {locale === 'zh' && <i className="bi bi-check2 ms-2"></i>}
          </button>
        </ul>
      </li>
    </ul>
  );
}
